function out = filter_bfs(img)

out = zeros(size(img));
maxQueue = zeros( size(img,1) * size(img,2),2) ; % queu with max elements size
currQueue = zeros( size(img,1) * size(img,2),2) ; % current running queue
cursor=1;
for x=1:size(img,1)
    for y=1:size(img,2)
        if img(x,y) > 0 % start bfs
            currQueue(cursor,:) = [x y];
            [currQueue img] = bfs2(img,currQueue);                         
            if (queueSize(currQueue) >  (queueSize(maxQueue)))
                maxQueue = currQueue;
            end
            currQueue=zeros( size(img,1) * size(img,2),2) ;
        end
    end
end

%% restore image
s = queueSize(maxQueue);
for i=1:s
    if ( maxQueue(i,1) > 0 && maxQueue(i,2) > 0)
        out(maxQueue(i,1),maxQueue(i,2))=1;
    else
        break;        
    end
end
end

function n = queueSize(q)
% return the custom queue size
n=0;
for i=1:size(q,1)    
    if ( q(i,1) > 0 &&  q(i,2)  > 0)
        n=i;
    else
        break;
    end
end
end

function [queue,newImg] = bfs2(img,q)
% bfs from starting point in q
zeroPlace=1;
place=2;
while ( q(zeroPlace,1) > 0 && q(zeroPlace,2) > 0 )
    for i=-1:1
        for j=-1:1
                x=q(zeroPlace,1) + i;
                y=q(zeroPlace,2)+ j;                
                if ( x > 0 && y > 0  && img(x,y) > 0 && x < size(img,1) && y < size(img,2) && img(x,y) > 0)                                                 
                    q(place,:) = [x,y];                                            
                    place=place+1;
                    img(x,y)=0;                    
                end
        end
    end
    zeroPlace=zeroPlace+1;
end
newImg = img;
queue =q;
end



